package cn.imvc.app.models;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Department;
import cn.imvc.app.entities.Department_position;
import cn.imvc.app.entities.Position;
import cn.imvc.app.repositories.DepartmentRepository;
import cn.imvc.app.repositories.PositionRepository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;
@Service
public class PositionModelImpl implements PositionModel {

	@Autowired
	private PositionRepository positionRepository;
	
	@Autowired
	private DepartmentRepository departmentRepository;
	
	public Page<Position> find(ViewRequest viewRequest) {
		return positionRepository.findAll(ModelUtil.OrderByIdDesc(viewRequest));
	}

	public Position get(int id) {
		return positionRepository.findOne(id);
	}

	public Position save(Position position) {
		return positionRepository.saveAndFlush(position);
	}

	public Position update(int id,Position position) {
		Position loadPosition=get(id);
		BeanUtils.copyProperties(position, loadPosition, "id");
		return positionRepository.saveAndFlush(loadPosition);
	}

	public void delete(int id) {
		positionRepository.delete(id);
		
	}

	public void deleteBatch(int[] ids) {
		for (int id : ids) {
			delete(id);
		}
		
	}

	public String treeLookup(int depid) {
		Department department=departmentRepository.findOne(depid);
		StringBuffer text = new StringBuffer();
		for (Object object: department.getDepartment_position()) {
			Department_position department_position=(Department_position)object;
			text.append("<li><a href=\"javascript:\" onclick=\"$.bringBack({code:'"+department_position.getPosition().getId()+"', name:'"+department_position.getPosition().getName()+"'})\">"+department_position.getPosition().getName()+"</a></li>");
		}
		return text.toString();
	}

	public String lookupSuggest(int depid) {
		Department department=departmentRepository.findOne(depid);
		StringBuffer text = new StringBuffer();
		text.append("[");
		int i=0;
		for (Object object: department.getDepartment_position()) {
			Department_position department_position=(Department_position)object;
			if(i==0){
				i++;
				text.append("{\"code\":\""+department_position.getPosition().getId()+"\", \"name\":\""+department_position.getPosition().getName()+"\"}");
			}else{
				text.append(",{\"code\":\""+department_position.getPosition().getId()+"\", \"name\":\""+department_position.getPosition().getName()+"\"}");
			}
		}
		text.append("]");
		return text.toString();
	}

}
